package com.xxkj.nmip.page;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.app.DownloadManager;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.CookieManager;
import com.tencent.smtt.sdk.DownloadListener;
import com.tencent.smtt.sdk.URLUtil;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.xxkj.nmip.R;
import com.xxkj.nmip.canstant.BaseCanstant;
import com.xxkj.nmip.dialog.ChooseDialog;
import com.xxkj.nmip.dialog.CommomDialog;
import com.xxkj.nmip.dialog.InputDialog;
import com.xxkj.nmip.js.JsApi;
import com.xxkj.nmip.js.JsEchoApi;
import com.xxkj.nmip.utils.AndroidBug5497Workaround;
import com.xxkj.nmip.utils.AppUtils;
import com.xxkj.nmip.utils.ClickUtils;
import com.xxkj.nmip.utils.DeviceIdUtil;
import com.xxkj.nmip.utils.DownloadCompleteReceiver;
import com.xxkj.nmip.utils.ToastUtils;

import java.io.File;

import wendu.dsbridge.DWebView;

import static android.os.Environment.DIRECTORY_PICTURES;

public class MainActivity extends BaseActivity {
    DWebView dwebView;
    Button bt_change_url;
    private ValueCallback<Uri> uploadFile;
    private ValueCallback<Uri[]> uploadFiles;
    private ViewGroup mViewParent;
    private String[] filechooseMore;
    private String cookieStr = "";
    private final int REQUEST_TAKE_RECORD = 52;
    private DownloadCompleteReceiver receiver;
    private String startUrl = "";
    public static final int WRITE_EXTERNAL_STORAGE_AND_CAMERA_REQUEST_CODE = 3;
    private Uri mImageUri;
    private File mFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AndroidBug5497Workaround.assistActivity(this);
        mViewParent = (ViewGroup) findViewById(R.id.webView1);
        bt_change_url = (Button) findViewById(R.id.bt_change_url);
        dwebView = new DWebView(this);
        mViewParent.addView(dwebView, new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.FILL_PARENT,
                FrameLayout.LayoutParams.FILL_PARENT));

        // set debug mode
        DWebView.setWebContentsDebuggingEnabled(true);
        dwebView.addJavascriptObject(new JsApi(this), null);
        dwebView.addJavascriptObject(new JsEchoApi(), "echo");
//        DownloadBlobFileJSInterface mDownloadBlobFileJSInterface = new DownloadBlobFileJSInterface(this);
//        dwebView.addJavascriptInterface(mDownloadBlobFileJSInterface, "Android");
//        dwebView.loadUrl("file:///android_asset/js-call-native.html");
//        dwebView.setBackgroundColor(R.color.transparent);
        //更换背景图片
//        dwebView.setBackgroundResource(R.mipmap.welcome);
        //dwebView.getSettingsExtension().setForcePinchScaleEnabled(true);
        // 使用
        receiver = new DownloadCompleteReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        registerReceiver(receiver, intentFilter);
        //文件下载
        dwebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(final String url, String userAgent, final String contentDisposition, final String mimeType, long contentLength) {
                try {
                    new CommomDialog(MainActivity.this, R.style.dialog, "是否下载该文件？", new CommomDialog.OnCloseListener() {
                        @Override
                        public void onClick(Dialog dialog, boolean confirm) {
                            if (confirm) {
                                ToastUtils.show(MainActivity.this, "开启下载了。。");
                                downloadBySystem(url, contentDisposition, mimeType);
                            }
                            dialog.dismiss();
                        }
                    }).setTitle("文件下载").show();


//                    if (url.contains("http://")&&url.contains("https://")) {
//                        Intent intent = new Intent(Intent.ACTION_VIEW);
//                        intent.addCategory(Intent.CATEGORY_BROWSABLE);
//                        intent.setData(Uri.parse(url));
//                        startActivity(intent);
//                    }else {
//                        // 3. 执行JS代码
//                        dwebView.loadUrl(DownloadBlobFileJSInterface.getBase64StringFromBlobUrl(url));
//                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        WebSettings webSetting = dwebView.getSettings();
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
//      webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
//        webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setDisplayZoomControls(false);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setAppCachePath(this.getDir("appcache", 0).getPath());
        webSetting.setDatabasePath(this.getDir("databases", 0).getPath());
        webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0)
                .getPath());
//       webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        dwebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);
                Log.v("tag", "url = " + url);
            }

            @Override
            public void onPageStarted(WebView webView, String url, Bitmap bitmap) {
                startUrl = url;
//                setChangeUrl(url);

                super.onPageStarted(webView, url, bitmap);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                checkShowChangeView(url);
                if (url.startsWith(BaseCanstant.OverrideUrl) || url.startsWith(BaseCanstant.LoginOutUrl) || url.equals(BaseCanstant.LoginOutUrl2) || url.startsWith(BaseCanstant.LoginOutUrl3)) {
                    dwebView.loadUrl(BaseCanstant.baseurl);
                }

                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView webView, String s) {
                return super.shouldInterceptRequest(webView, s);
            }

            @Override
            public void onPageFinished(WebView webView, String s) {
                super.onPageFinished(webView, s);
                CookieManager cookieManager = CookieManager.getInstance();
                cookieStr = cookieManager.getCookie(s); // 获取到cookie字符串值
                checkShowChangeView(s);
            }
        });
        dwebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public boolean onJsConfirm(WebView arg0, String arg1, String arg2,
                                       JsResult arg3) {
                return super.onJsConfirm(arg0, arg1, arg2, arg3);
            }

            View myVideoView;
            View myNormalView;
            IX5WebChromeClient.CustomViewCallback callback;

            /**
             * 全屏播放配置
             */
            @Override
            public void onShowCustomView(View view,
                                         IX5WebChromeClient.CustomViewCallback customViewCallback) {
                FrameLayout normalView = (FrameLayout) findViewById(R.id.webView1);
                ViewGroup viewGroup = (ViewGroup) normalView.getParent();
                viewGroup.removeView(normalView);
                viewGroup.addView(view);
                myVideoView = view;
                myNormalView = normalView;
                callback = customViewCallback;
            }

            @Override
            public void onHideCustomView() {
                if (callback != null) {
                    callback.onCustomViewHidden();
                    callback = null;
                }
                if (myVideoView != null) {
                    ViewGroup viewGroup = (ViewGroup) myVideoView.getParent();
                    viewGroup.removeView(myVideoView);
                    viewGroup.addView(myNormalView);
                }
            }

            @Override
            public boolean onJsAlert(WebView arg0, String arg1, String arg2,
                                     JsResult arg3) {
                /**
                 * 这里写入你自定义的window alert
                 */
                return super.onJsAlert(null, arg1, arg2, arg3);
            }

            /**
             * 防止加载网页时调起系统浏览器
             */
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            // For Android 3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                Log.i("test", "openFileChooser 1");
                uploadFile = uploadFile;
                openFileChooseProcess();
            }

            // For Android < 3.0
            public void openFileChooser(ValueCallback<Uri> uploadMsgs) {
                Log.i("test", "openFileChooser 2");
                uploadFile = uploadFile;
                openFileChooseProcess();
            }

            // For Android  > 4.1.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                Log.i("test", "openFileChooser 3");
                uploadFile = uploadFile;

                openFileChooseProcess();
            }

            // For Android  >= 5.0
            public boolean onShowFileChooser(WebView webView,
                                             ValueCallback<Uri[]> filePathCallback,
                                             FileChooserParams fileChooserParams) {
                Log.i("test", "openFileChooser 4:" + filePathCallback.toString());
                filechooseMore = null;
                if (fileChooserParams != null && fileChooserParams.getAcceptTypes() != null
                        && fileChooserParams.getAcceptTypes().length > 0) {
                    filechooseMore = fileChooserParams.getAcceptTypes();
                } else {
                }
                uploadFiles = filePathCallback;
                new ChooseDialog(MainActivity.this, R.style.dialog, "", new ChooseDialog.OnCloseListener() {
                    @Override
                    public void onClick(Dialog dialog, boolean confirm, String content) {
                        if (confirm) {
                            if ("1".equals(content)) {
                                openFileChooseProcess();
                            } else if ("2".equals(content)) {
                                takePic();
                            } else if ("3".equals(content)) {
                                if (null != uploadFile) {
                                    uploadFile.onReceiveValue(null);
                                    uploadFile = null;
                                }
                                if (null != uploadFiles) {
                                    uploadFiles.onReceiveValue(null);
                                    uploadFiles = null;
                                }
                            }
                        }
                        dialog.dismiss();
                    }
                }).show();
                return true;
            }

        });


        String baseurl_js = getIntent().getStringExtra("baseurl_js");
        if (!TextUtils.isEmpty(baseurl_js)) {
            BaseCanstant.baseurl = baseurl_js;
        } else {
            BaseCanstant.baseurl = BaseCanstant.baseurl_pre;
        }
        if (BaseCanstant.baseurl.endsWith("?")){
            dwebView.loadUrl(BaseCanstant.baseurl+"r="+ AppUtils.getRandomNum(8));
        }else
            dwebView.loadUrl(BaseCanstant.baseurl+"?r="+ AppUtils.getRandomNum(8));
        Log.e("设备唯一标识", DeviceIdUtil.getDeviceId(this));
        initListener();
    }

    private void checkShowChangeView(String url) {
        if (url.contains("yySSO/index.html#/login")||url.contains("/app/mobile/login/login")){
            bt_change_url.setVisibility(View.VISIBLE);
        }else   bt_change_url.setVisibility(View.GONE);

    }
    private void initListener() {
        bt_change_url.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new InputDialog(MainActivity.this, R.style.dialog, BaseCanstant.baseurl, new InputDialog.OnCloseListener() {
                    @Override
                    public void onClick(Dialog dialog, boolean confirm, String content) {
                        if (confirm) {
                            Intent intent = new Intent();
                            intent.setClass(MainActivity.this, MainActivity.class);
                            intent.putExtra("baseurl_js", content);
                            startActivity(intent);
                            finish();
                        }
                        dialog.dismiss();
                    }
                }).setTitle("确认更改地址?").show();
            }
        });
    }


    private void openFileChooseProcess() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        if (filechooseMore != null && filechooseMore.length > 0) {


            i.setType("*/*");
            if (filechooseMore != null) {
                for (String filetype : filechooseMore) {
                    if (filetype.contains("video")) {
                        i.setType("video/*");
                    } else if (filetype.contains("image")) {
                        i.setType("image/*");
                    } else if (filetype.contains("docx") || filetype.contains("doc") || filetype.contains("ppt") || filetype.contains("pptx") || filetype.contains("xlsx") || filetype.contains("xls") || filetype.contains("pdf")) {
                        i.setType("*/*");
                    }
                }

            }
//            i .putExtra(Intent.EXTRA_MIME_TYPES, filechooseMore);
//            i .addCategory(Intent.CATEGORY_OPENABLE);


        } else {
            i.setType("*/*");
        }

        startActivityForResult(Intent.createChooser(i, "test"), 0);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (!ClickUtils.isFastClick()) {
            quite();
        } else {
            if ((keyCode == KeyEvent.KEYCODE_BACK) && dwebView != null && dwebView.canGoBack()) {
                if (startUrl.equals(BaseCanstant.baseurl) || startUrl.equals(BaseCanstant.LoginOutUrl)) {
                    quite();
                } else {
                    dwebView.goBack(); // goBack()表示返回WebView的上一页面
                }

                return true;
            } else if (keyCode == KeyEvent.KEYCODE_BACK) {
                quite();

            }
        }

        return super.onKeyDown(keyCode, event);
    }

    private void quite() {
        new CommomDialog(this, R.style.dialog, "确认退出？", new CommomDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    finish();
                }
                dialog.dismiss();
            }
        }).setTitle("").show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 0:
                    if (null != uploadFile) {
                        Uri result = data == null || resultCode != RESULT_OK ? null
                                : data.getData();
                        uploadFile.onReceiveValue(result);
                        uploadFile = null;
                    }
                    if (null != uploadFiles) {
                        Uri result = data == null || resultCode != RESULT_OK ? null
                                : data.getData();
                        uploadFiles.onReceiveValue(new Uri[]{result});
                        uploadFiles = null;
                    }
                    break;
                case REQUEST_TAKE_RECORD:
                    String dataFile = data.getDataString();
                    Log.e("datafile", "dataFile: " + dataFile);
                    break;
                case 112:
                    if (null != uploadFiles) {
                        uploadFiles.onReceiveValue(new Uri[]{mImageUri});
                        uploadFiles = null;
                    }
                    break;
                default:
                    break;
            }
        } else if (resultCode == RESULT_CANCELED) {
            if (null != uploadFile) {
                uploadFile.onReceiveValue(null);
                uploadFile = null;
            }
            if (null != uploadFiles) {
                Uri result = data == null || resultCode != RESULT_OK ? null
                        : data.getData();
                uploadFiles.onReceiveValue(null);
                uploadFiles = null;
            }

        }
    }

    private void downloadBySystem(String url, String contentDisposition, String mimeType) {
        if (!url.startsWith("http://") && !url.startsWith("https://")) {
            url = "http://" + url;
        }
        // 指定下载地址
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        // 允许媒体扫描，根据下载的文件类型被加入相册、音乐等媒体库
        request.allowScanningByMediaScanner();
        // 设置通知的显示类型，下载进行时和完成后显示通知
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        // 设置通知栏的标题，如果不设置，默认使用文件名
//        request.setTitle("This is title");
        // 设置通知栏的描述
//        request.setDescription("This is description");
        // 允许在计费流量下下载
        request.setAllowedOverMetered(false);
        // 允许该记录在下载管理界面可见
        request.setVisibleInDownloadsUi(false);
        // 允许漫游时下载
        request.setAllowedOverRoaming(true);
        // 允许下载的网路类型
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        // 设置下载文件保存的路径和文件名
        String fileName = URLUtil.guessFileName(url, contentDisposition, mimeType);
//                    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
//        另外可选一下方法，自定义下载路径
//        request.setDestinationUri()
//        request.setDestinationInExternalFilesDir()
        request.setDestinationInExternalFilesDir(MainActivity.this, Environment.DIRECTORY_DOWNLOADS, fileName);
        final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        // 添加一个下载任务
        long downloadId = downloadManager.enqueue(request);
    }

    protected void onDestroy() {
        super.onDestroy();
        //特别注意：在退出界面的时候，动态注册广播要解绑
        if (receiver != null) {
            unregisterReceiver(receiver);
        }

    }


    /**
     * 拍照
     */
    public void takePic() {
        try {
            String state = Environment.getExternalStorageState();
            if (state.equals(Environment.MEDIA_MOUNTED)) {
                Intent cameraIntent = new Intent();
                mFile = new File(Environment.getExternalStoragePublicDirectory(DIRECTORY_PICTURES), "temp.jpg");
                ///storage/emulated/0/Pictures/temp.jpg
                mImageUri = Uri.fromFile(mFile);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    //content://com.example.shinelon.takephotodemo.provider/camera_photos/Pictures/temp.jpg
                    mImageUri = FileProvider.getUriForFile(this, getPackageName() + ".provider", mFile);
                }
                //指定照片保存路径（SD卡），temp.jpg为一个临时文件，每次拍照后这个图片都会被替换
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
                cameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                cameraIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);

//                cameraIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                startActivityForResult(cameraIntent, 112);
            } else {
                Toast toast = Toast.makeText(this, "请确认已经插入SD卡", Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 检查存储权限 和 相机权限
     *
     * @return true, 已经获取权限;false,没有权限,尝试获取
     */
    private boolean checkStorageAndCameraPermission() {
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions((Activity) MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA,},
                    WRITE_EXTERNAL_STORAGE_AND_CAMERA_REQUEST_CODE);
            return false;
        } else {
            return true;
        }
    }
}
